package comprehension.cn.edu.scau.cmi.huxiantao.client;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;

import comprehension.cn.edu.scau.cmi.huxiantao.dao.StudentDAO;
import comprehension.cn.edu.scau.cmi.huxiantao.dao.TeacherDAO;
import comprehension.cn.edu.scau.cmi.huxiantao.domain.Student;
import comprehension.cn.edu.scau.cmi.huxiantao.domain.Teacher;
import comprehension.cn.edu.scau.cmi.huxiantao.util.ApplicationContextFactory;
import comprehension.cn.edu.scau.cmi.huxiantao.util.SessionFactoryUtil;
import comprehension.cn.edu.scau.cmi.huxiantao.util.TableInfo;
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.ButtonType;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;

public class ComprehensionJavaFxClient extends Application implements Initializable{
	@FXML
	private TextField textField_sid1;
	@FXML
	private TextField textField_sname1;
	@FXML
	private TextField textField_tid1;
	@FXML
	private TextField textField_tname1;
	@FXML
	private TextField textField_tid2;
	@FXML
	private TextField textField_tname2;
	@FXML
	private TextField textField_sid2;
	@FXML
	private TextField textField_sname2;
	@FXML
	private TableView<TableInfo> tableView_student;
	@FXML
	private TableView<TableInfo> tableView_teacher;
	@FXML
	private TableView<TableInfo> tableView_teacher_sub;
	
	private List<Teacher> teachers=new ArrayList<Teacher>();
	
	@Override
	public void start(Stage stage) throws Exception {
		SessionFactoryUtil.getSessionFactory();
		Parent root=FXMLLoader.load(this.getClass().getResource("/comprehension/gui.fxml"));
		Scene scene=new Scene(root);
		stage.setScene(scene);
		stage.setTitle("实验9 Spring集成Hibernate基本使用");
		stage.show();
	}

	public static void main(String[] args) {
		launch();
	}
	
	@FXML
	public void addStudent() {
		if (textField_sid1.getText().equals("")||textField_sname1.getText().equals("")) {
			return;
		}
		Teacher teacher=null;
		Student student=null;
		
		int sid = Integer.parseInt(textField_sid1.getText());
		String sname = textField_sname1.getText();
		
		if (!textField_tid1.getText().equals("")&&!textField_tname1.getText().equals("")) {
			int tid = Integer.parseInt(textField_tid1.getText());
			String tname = textField_tname1.getText();
			teacher=new Teacher(tid,tname);
		}
		student=new Student(sid,sname,teacher);
		
		StudentDAO dao=(StudentDAO)ApplicationContextFactory.getContext().getBean("studentDAO");
		boolean successful=dao.save(student);
		
		if (successful) {
			findAllStudents();
			Alert alert = new Alert(AlertType.NONE, "操作成功", ButtonType.OK);
			alert.showAndWait();
		}else {
			Alert alert = new Alert(AlertType.ERROR, "操作失败", ButtonType.CANCEL);
			alert.showAndWait();
		}
	}
	
	@FXML
	public void deleteStudent() {
		if (textField_sid1.getText().equals("")||textField_sname1.getText().equals("")) {
			return;
		}
		Teacher teacher=null;
		Student student=null;
		
		int sid = Integer.parseInt(textField_sid1.getText());
		String sname = textField_sname1.getText();
		
		if (!textField_tid1.getText().equals("")&&!textField_tname1.getText().equals("")) {
			int tid = Integer.parseInt(textField_tid1.getText());
			String tname = textField_tname1.getText();
			teacher=new Teacher(tid,tname);
		}
		student=new Student(sid,sname,teacher);
		
		StudentDAO dao=(StudentDAO)ApplicationContextFactory.getContext().getBean("studentDAO");
		boolean successful=dao.delete(student);
		
		if (successful) {
			findAllStudents();
			Alert alert = new Alert(AlertType.NONE, "操作成功", ButtonType.OK);
			alert.showAndWait();
		}else {
			Alert alert = new Alert(AlertType.ERROR, "操作失败", ButtonType.CANCEL);
			alert.showAndWait();
		}
	}
	
	@FXML
	public void updateStudent() {
		if (textField_sid1.getText().equals("")||textField_sname1.getText().equals("")) {
			return;
		}
		Teacher teacher=null;
		Student student=null;
		
		int sid = Integer.parseInt(textField_sid1.getText());
		String sname = textField_sname1.getText();
		
		if (!textField_tid1.getText().equals("")&&!textField_tname1.getText().equals("")) {
			int tid = Integer.parseInt(textField_tid1.getText());
			String tname = textField_tname1.getText();
			teacher=new Teacher(tid,tname);
		}
		student=new Student(sid,sname,teacher);
		
		StudentDAO dao=(StudentDAO)ApplicationContextFactory.getContext().getBean("studentDAO");
		boolean successful=dao.update(student);
		
		if (successful) {
			findAllStudents();
			Alert alert = new Alert(AlertType.NONE, "操作成功", ButtonType.OK);
			alert.showAndWait();
		}else {
			Alert alert = new Alert(AlertType.ERROR, "操作失败", ButtonType.CANCEL);
			alert.showAndWait();
		}
	}
	
	@FXML
	public void findStudent() {
		StudentDAO dao=(StudentDAO)ApplicationContextFactory.getContext().getBean("studentDAO");
		List<Student> students=new ArrayList<Student>();
		if(!textField_sid1.getText().equals("")) {
			Student student=dao.findById(Integer.parseInt(textField_sid1.getText()));
			if(student!=null)
				students.add(student);
		}else if(!textField_sname1.getText().equals("")) {
			students=dao.findByProperty("name", textField_sname1.getText());
		}
		tableView_student.setItems(TableInfo.transformStudentList(students));
	}
	
	@FXML
	public void findAllStudents() {
		StudentDAO dao=(StudentDAO)ApplicationContextFactory.getContext().getBean("studentDAO");
		List<Student> students=dao.findAll();
		tableView_student.setItems(TableInfo.transformStudentList(students));
	}
	
	@FXML
	public void addTeacher() {
		if(textField_tid2.getText().equals("")||textField_tname2.getText().equals("")) {
			return;
		}
		int tid=Integer.parseInt(textField_tid2.getText());
		String tname=textField_tname2.getText();
		Teacher teacher=new Teacher(tid,tname);
		
		TeacherDAO dao=(TeacherDAO)ApplicationContextFactory.getContext().getBean("teacherDAO");
		boolean successful=dao.save(teacher);
		
		if (successful) {
			findAllTeachers();
			Alert alert = new Alert(AlertType.NONE, "操作成功", ButtonType.OK);
			alert.showAndWait();
		}else {
			Alert alert = new Alert(AlertType.ERROR, "操作失败", ButtonType.CANCEL);
			alert.showAndWait();
		}
	}
	
	@FXML
	public void deleteTeacher() {
		if(textField_tid2.getText().equals("")||textField_tname2.getText().equals("")) {
			return;
		}
		int tid=Integer.parseInt(textField_tid2.getText());
		String tname=textField_tname2.getText();
		Teacher teacher=new Teacher(tid,tname);
		
		TeacherDAO dao=(TeacherDAO)ApplicationContextFactory.getContext().getBean("teacherDAO");
		boolean successful=dao.delete(teacher);
		
		if (successful) {
			findAllTeachers();
			Alert alert = new Alert(AlertType.NONE, "操作成功", ButtonType.OK);
			alert.showAndWait();
		}else {
			Alert alert = new Alert(AlertType.ERROR, "操作失败", ButtonType.CANCEL);
			alert.showAndWait();
		}
	}
	
	@FXML
	public void updateTeacher() {
		if(textField_tid2.getText().equals("")||textField_tname2.getText().equals("")) {
			return;
		}
		int tid=Integer.parseInt(textField_tid2.getText());
		String tname=textField_tname2.getText();
		Teacher teacher=new Teacher(tid,tname);
		
		TeacherDAO dao=(TeacherDAO)ApplicationContextFactory.getContext().getBean("teacherDAO");
		boolean successful=dao.update(teacher);
		
		if (successful) {
			findAllTeachers();
			Alert alert = new Alert(AlertType.NONE, "操作成功", ButtonType.OK);
			alert.showAndWait();
		}else {
			Alert alert = new Alert(AlertType.ERROR, "操作失败", ButtonType.CANCEL);
			alert.showAndWait();
		}
	}
	
	@FXML
	public void findTeacher() {
		TeacherDAO dao=(TeacherDAO)ApplicationContextFactory.getContext().getBean("teacherDAO");
		List<Teacher> teachers=new ArrayList<Teacher>();
		if(!textField_tid2.getText().equals("")) {
			Teacher teacher=dao.findById(Integer.parseInt(textField_tid2.getText()));
			if(teacher!=null)
				teachers.add(teacher);
		}else if(!textField_tname2.getText().equals("")) {
			teachers=dao.findByProperty("name", textField_tname2.getText());
		}
		this.teachers=teachers;
		tableView_teacher.setItems(TableInfo.transformTeacherList(teachers));
	}
	
	@FXML
	public void findAllTeachers() {
		TeacherDAO dao=(TeacherDAO)ApplicationContextFactory.getContext().getBean("teacherDAO");
		List<Teacher> teachers=dao.findAll();
		this.teachers=teachers;
		tableView_teacher.setItems(TableInfo.transformTeacherList(teachers));
	}
	
	@FXML
	public void addStudent2Teach() {
		if(textField_sid2.getText().equals("")||textField_tid2.getText().equals("")) {
			return;
		}
		int sid=Integer.parseInt(textField_sid2.getText());
		int tid=Integer.parseInt(textField_tid2.getText());
		
	    StudentDAO sdao=(StudentDAO)ApplicationContextFactory.getContext().getBean("studentDAO");
		TeacherDAO tdao=(TeacherDAO)ApplicationContextFactory.getContext().getBean("teacherDAO");
		
		Teacher teacher=tdao.findById(tid);
		Student student=sdao.findById(sid);
		student.setTeacher(teacher);
		
	    boolean successful=sdao.update(student);
		
		if (successful) {
			findTeacher();
			tableView_teacher.getSelectionModel().select(0);
			Alert alert = new Alert(AlertType.NONE, "操作成功", ButtonType.OK);
			alert.showAndWait();
		}else {
			Alert alert = new Alert(AlertType.ERROR, "操作失败", ButtonType.CANCEL);
			alert.showAndWait();
		}
	}
	
	@FXML
	public void deleteStudent2Teach() {
		if(textField_sid2.getText().equals("")||textField_tid2.getText().equals("")) {
			return;
		}
		int sid=Integer.parseInt(textField_sid2.getText());
		int tid=Integer.parseInt(textField_tid2.getText());

	    StudentDAO sdao=(StudentDAO)ApplicationContextFactory.getContext().getBean("studentDAO");
		TeacherDAO tdao=(TeacherDAO)ApplicationContextFactory.getContext().getBean("teacherDAO");
		
		boolean successful=false;
		Teacher teacher=tdao.findById(tid);
		Student student=sdao.findById(sid);
		if(student!=null&&teacher!=null&&student.getTeacher().getId()==teacher.getId()) {
			student.setTeacher(null);
			successful=sdao.update(student);
		}
		
		if (successful) {
			findTeacher();
			tableView_teacher.getSelectionModel().select(0);
			Alert alert = new Alert(AlertType.NONE, "操作成功", ButtonType.OK);
			alert.showAndWait();
		}else {
			Alert alert = new Alert(AlertType.ERROR, "操作失败", ButtonType.CANCEL);
			alert.showAndWait();
		}
	}

	@Override
	public void initialize(URL location, ResourceBundle resources) {
		ObservableList<TableColumn<TableInfo,?>> stuCols=tableView_student.getColumns();
		ObservableList<TableColumn<TableInfo,?>> thCols=tableView_teacher.getColumns();
		ObservableList<TableColumn<TableInfo,?>> thSubCols=tableView_teacher_sub.getColumns();
		
		stuCols.get(0).setCellValueFactory(new PropertyValueFactory<>("studentId"));
		stuCols.get(1).setCellValueFactory(new PropertyValueFactory<>("studentName"));
		stuCols.get(2).setCellValueFactory(new PropertyValueFactory<>("teacherId"));
		stuCols.get(3).setCellValueFactory(new PropertyValueFactory<>("teacherName"));
		
		thCols.get(0).setCellValueFactory(new PropertyValueFactory<>("teacherId"));
		thCols.get(1).setCellValueFactory(new PropertyValueFactory<>("teacherName"));
		
		thSubCols.get(0).setCellValueFactory(new PropertyValueFactory<>("studentId"));
		thSubCols.get(1).setCellValueFactory(new PropertyValueFactory<>("studentName"));
		
		tableView_student.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<TableInfo>() {
			@Override
			public void changed(ObservableValue<? extends TableInfo> observable, TableInfo oldValue,
					TableInfo newValue) {
				if (newValue != null) {
					textField_sid1.setText(String.valueOf(newValue.getStudentId()));
					textField_sname1.setText(newValue.getStudentName());
					textField_tid1.setText(newValue.getTeacherId());
					textField_tname1.setText(newValue.getTeacherName());
				}
			}
		});
		
		tableView_teacher.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<TableInfo>() {
			@Override
			public void changed(ObservableValue<? extends TableInfo> observable, TableInfo oldValue,
					TableInfo newValue) {
				if (newValue != null) {
					textField_tid2.setText(newValue.getTeacherId());
					textField_tname2.setText(newValue.getTeacherName());
					
					List<Student> students=new ArrayList<>();
					teachers.forEach(t->{
						if(t.getId()==Integer.parseInt(newValue.getTeacherId())) {
							students.addAll(t.getStudents());
						}
					});
					tableView_teacher_sub.setItems(TableInfo.transformStudentList(students));
				}
			}
		});
		
		tableView_teacher_sub.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<TableInfo>() {

			@Override
			public void changed(ObservableValue<? extends TableInfo> observable, TableInfo oldValue,
					TableInfo newValue) {
				if(newValue!=null) {
					textField_sid2.setText(String.valueOf(newValue.getStudentId()));
					textField_sname2.setText(newValue.getStudentName());
				}
			}
			
		});
	}
}
